package xyz.csmcool.imroom.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.jsonwebtoken.Jwt;
import lombok.RequiredArgsConstructor;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import xyz.csmcool.imroom.entity.Rooms;
import xyz.csmcool.imroom.entity.vo.RoomSimpleVo;
import xyz.csmcool.imroom.feignclient.OssClint;
import xyz.csmcool.imroom.service.IRoomsService;
import xyz.csmcool.imutil.dto.UserDto;
import xyz.csmcool.imutil.utils.JwtUtils;
import xyz.csmcool.imutil.utils.ResultTool;
import xyz.csmcool.imutil.utils.SecretUtils;
import xyz.csmcool.imutil.webVo.MyPage;
import xyz.csmcool.imutil.webVo.ResultCode;
import xyz.csmcool.imutil.webVo.ResultVo;

import javax.management.Query;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author csmcool
 * @since 2022-08-06
 */
@RestController
@RequestMapping("/rooms")
@RequiredArgsConstructor
public class RoomsController {

    final OssClint ossClint;
    final IRoomsService roomsService;


    @PostMapping("/add-room")
    public ResultVo addRoom(@RequestParam(value = "coverImage",required = false)MultipartFile multipartFile,
                            @RequestParam("name") String name,
                            @RequestParam("description") String description,
                            @RequestParam(value = "slug",required = false) String slug,
                            @RequestParam(value = "isProtected",required = false) Boolean isProtected,
                            @RequestParam(value = "password",required = false) String password,
                            @RequestParam(value = "isVisible",required = false) Boolean isVisible,
                            @RequestParam(value = "status",required = false) Integer status, HttpServletRequest httpServletRequest) {
        ResultVo<HashMap<String, String>>  resultVo;
        Rooms rooms = new Rooms();
        if (multipartFile != null) {
            resultVo = ossClint.uploadRoomFile(multipartFile);
            if (!resultVo.getSucceed()) {
                return resultVo;
            }
            rooms.setCoverImage(resultVo.getData().get("url"));
        }
        rooms.setName(name);
        rooms.setDescription(description);
        rooms.setSlug(slug);
        rooms.setIsProtected(isProtected);
        if(password == null) {
            password = SecretUtils.encrypt("123456");
        } else if(isProtected) {
            password = SecretUtils.encrypt(password);
        }
        rooms.setPassword(password);
        rooms.setIsVisible(isVisible);
        rooms.setStatus(status);
        String userId = JwtUtils.getMemberIdByJwtToken(httpServletRequest);
        rooms.setCreatedBy(Integer.valueOf(userId));
        boolean saveOrUpdate = roomsService.createRoom(rooms);
        if (!saveOrUpdate) {
            return ResultTool.fail(ResultCode.CUSTOM_FAIL.setMessage("创建房间出了点小问题"));
        }

        return ResultTool.success();
    }

    @GetMapping("/my-room/{limit}/{page}")
    public ResultVo<MyPage<Rooms>> getMyRoom(@PathVariable("limit") Long limit,
                              @PathVariable("page") Long page,HttpServletRequest request) {
        String id = JwtUtils.getMemberIdByJwtToken(request);
        MyPage<Rooms> rooms = roomsService.selectMyRooms(page, limit, Integer.valueOf(id));
        return ResultTool.success(rooms);
    }

    @GetMapping("/admin/all-room/{limit}/{page}")
    public ResultVo<MyPage<Rooms>> getAllRooms(@PathVariable("limit") Long limit,
                              @PathVariable("page") Long page) {
        MyPage<Rooms> rooms = roomsService.selectAllRooms(page, limit);
        return ResultTool.success(rooms);
    }

    @GetMapping("/search-room/{limit}/{page}/{name}")
    public ResultVo<MyPage<Rooms>> searchRoom(@PathVariable("limit") Long limit,
                                              @PathVariable("page") Long page, @PathVariable("name") String name,
                                              HttpServletRequest request) {
        String id = JwtUtils.getMemberIdByJwtToken(request);
        MyPage<Rooms> rooms = roomsService.searchRoom(page, limit, name, Integer.valueOf(id));
        return ResultTool.success(rooms);
    }

    @PutMapping("/update-room")
    public ResultVo updateRoom(@RequestParam(value = "coverImage",required = false)MultipartFile multipartFile,
                            @RequestParam(value = "name",required = false) String name,
                            @RequestParam(value = "description",required = false) String description,
                            @RequestParam(value = "slug",required = false) String slug,
                            @RequestParam(value = "isProtected",required = false) Boolean isProtected,
                            @RequestParam(value = "password",required = false) String password,
                            @RequestParam(value = "isVisible",required = false) Boolean isVisible,
                            @RequestParam(value = "id",required = true) Integer id,
                            @RequestParam(value = "status",required = false) Integer status, HttpServletRequest httpServletRequest) {
        ResultVo<HashMap<String, String>>  resultVo = new ResultVo<>();
        Rooms rooms = new Rooms();
        if (multipartFile != null) {
            resultVo = ossClint.uploadRoomFile(multipartFile);
            if (!resultVo.getSucceed()) {
                return resultVo;
            }
            rooms.setCoverImage(resultVo.getData().get("url"));
        }
        rooms.setName(name);
        rooms.setDescription(description);
        rooms.setSlug(slug);
        rooms.setIsProtected(isProtected);
        rooms.setPassword(password);
        rooms.setIsVisible(isVisible);
        rooms.setStatus(status);
        String userId = JwtUtils.getMemberIdByJwtToken(httpServletRequest);
        rooms.setId(id);
        QueryWrapper<Rooms> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("created_by",userId);
        boolean saveOrUpdate = roomsService.update(rooms,queryWrapper);
        if (!saveOrUpdate) {
            return ResultTool.fail(ResultCode.CUSTOM_FAIL.setMessage("更新房间出了点小问题"));
        }
        return ResultTool.success();
    }

    @DeleteMapping("/delete-room/{roomId}")
    public ResultVo deleteRoom(@PathVariable("roomId") Integer roomId,HttpServletRequest httpServletRequest) {
        String userId = JwtUtils.getMemberIdByJwtToken(httpServletRequest);
        roomsService.deleteRoom(roomId,Integer.valueOf(userId));
        return ResultTool.success();
    }

    @GetMapping("/public-room/{limit}/{page}/{sortType}/{name}")
    public ResultVo<MyPage<Rooms>> getPublicRoom(@PathVariable("limit") Long limit,
                                                           @PathVariable("page") Long page,
                                                           @PathVariable("sortType") Integer sortType,
                                                           @PathVariable("name") String name){
        MyPage<Rooms> rooms = roomsService.publicRoom(page, limit, name, sortType);
        return ResultTool.success(rooms);
    }

    @GetMapping("/get-join-room/{limit}/{page}")
    public ResultVo<MyPage<Rooms>> getMyJoinRoom(@PathVariable("limit") Long limit,
                                                 @PathVariable("page") Long page,
                                                 HttpServletRequest request) {
        String id = JwtUtils.getMemberIdByJwtToken(request);
        MyPage<Rooms> rooms = roomsService.getMyRoom(page, limit, Integer.valueOf(id));
        return ResultTool.success(rooms);
    }

    @GetMapping("/get-join-room/{limit}/{page}/{name}")
    public ResultVo<MyPage<Rooms>> searchMyJoinRoom(@PathVariable("limit") Long limit,
                                                    @PathVariable("page") Long page,
                                                    @PathVariable String name,
                                                    HttpServletRequest request) {
        String id = JwtUtils.getMemberIdByJwtToken(request);
        MyPage<Rooms> rooms = roomsService.searchMyRoom(page, limit, Integer.valueOf(id),name);
        return ResultTool.success(rooms);
    }

    @GetMapping("getMyRoomInfo/{id}")
    public ResultVo<RoomSimpleVo> getMyJoinRoomSimpleInfo(@PathVariable("id") Integer id) {
        return ResultTool.success(roomsService.getMySimpleRoomInfo(id));
    }

    @GetMapping("/is-myroom")
    public ResultVo isMyRoom(@RequestParam("id") Integer roomId,@RequestParam("uid") Integer uid){
        Boolean myRoom = roomsService.isMyRoom(roomId, uid);
        if(myRoom) {
            return ResultTool.success();
        }
        return ResultTool.fail();
    }
}
